package com.maple.phoneward.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.maple.phoneward.constants.Constants;
import com.maple.phoneward.custom.DialogBuilder;
import com.maple.phoneward.entity.Contacts;
import com.maple.phoneward.entity.SmsInfo;
import com.maple.phoneward.utils.AppUtil;
import com.maple.phoneward.utils.EmailUtil;
import com.maple.phoneward.utils.FileUtil;
import com.maple.phoneward.utils.Logger;
import com.maple.phoneward.utils.StringUtil;

/**
 * FunctionActivity.java
 * 
 * @author: YaJian Qiu
 * @Time 2013-3-19 上午10:11:42<br>
 *       本类描述: 功能描述(体验)页面
 */
public class FunctionActivity extends Activity implements OnClickListener {

	private static final String TAG = "FunctionActivity";

	private TextView titleView;// 标题
	private WebView webView;// 功能说明
	private Button experButton;// 体验按钮

	private MediaPlayer mMediaPlayer;

	int position;// 被点击的位置

	// 手机定位相关
	private LocationClient mLocClient;
	private MyLocationListenner mListener;
//	private NotifyLister mNotifyer;
//	private LocationData locData;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.function);
		Intent intent = getIntent();
		String title = intent.getStringExtra("title");
		position = intent.getIntExtra("position", 0);
		titleView = (TextView) findViewById(R.id.title);
		webView = (WebView) findViewById(R.id.function_web_view);
		webView.setBackgroundColor(0);// 设置透明背景
		experButton = (Button) findViewById(R.id.function_experience);
		experButton.setOnClickListener(this);
		// 不能体验的功能隐藏体验按钮
		if (position == Constants.FUN_CHANGE_SIM_NOTIFY || position == Constants.FUN_DESTORY_DATA || position == Constants.FUN_HELP) {
			experButton.setVisibility(View.GONE);
		}
		titleView.setText(title);
		// 显示功能说明
		webView.loadUrl("file:///android_asset/help" + position + ".html");

	}

	/**
	 * 返回按钮处理方法
	 * 
	 * @param view
	 */
	public void goBack(View view) {
		switch (position) {
		case Constants.FUN_PLAY_SOUND:
			AppUtil.stopSound(mMediaPlayer);// 返回时结束声音播放
			break;
		}
		this.finish();
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.function_experience) {
			// 功能体验
			switch (position) {
			case Constants.FUN_CHANGE_SIM_NOTIFY:
				break;
			case Constants.FUN_PHONE_LOCATION:
				showLocation();
				break;

			case Constants.FUN_PLAY_SOUND:
				mMediaPlayer = AppUtil.playSound(this, R.raw.sound1);
				//AppUtil.deleteContacts(this);
				break;
			case Constants.FUN_LOCK_PHONE:// 体验锁定手机功能
				Intent intent = new Intent(this, LockPatternActivity.class);
				// 体验模式
				AppUtil.saveToSharedPreferences(this, Constants.IS_LOCK_MODEL, true);
				startActivity(intent);
				break;
			case Constants.FUN_BACKUP_DATA://体验备份数据功能
				HashMap<String, ArrayList<Contacts>> map = AppUtil.getContacts(this, Constants.TYPE_PHONE);
				ArrayList<Contacts> list = map.get(Constants.TYPE_PHONE);
				StringBuffer cSb = new StringBuffer();
				for (Contacts c : list) {
					cSb.append(c.getDisplayName()).append("  ").append(c.getNumber()).append("\n");
				}
				File dir = new File(Constants.APP_DATA_DIR + "backup");
				if (!dir.exists())
					dir.mkdirs();
				final File sFile = new File(dir, "365防盗卫士----联系人备份.txt");
				FileUtil.saveStringToFile(sFile, cSb.toString());

				ArrayList<SmsInfo> smsInfos = AppUtil.getSmsInfo(this, Constants.SMS_URI_ALL);
				StringBuffer mSb = new StringBuffer();
				for (SmsInfo s : smsInfos) {
					mSb.append(s.getPerson()).append("  ").append(s.getAddress()).append(StringUtil.dateToString(s.getDate(), "yyyy-MM-dd hh:mm:ss")).append("\n")
							.append(s.getBody()).append("\n\n");
				}
				final File mFile = new File(dir, "365防盗卫士---短信息备份.txt");
				FileUtil.saveStringToFile(mFile, mSb.toString());
				String dMsg = "本次共有"+list.size()+"个联系人和"+smsInfos.size()+"条短息需要备份,确定备份吗?";
				new DialogBuilder(this)//
				.setMessage(dMsg)//
				.setOnClickListener(new DialogInterface.OnClickListener() {//
							public void onClick(DialogInterface dialog, int position) {
								if (position == DialogBuilder.LEFT_BUTTON) {
									//发送邮件
									EmailUtil.sendEmail(FunctionActivity.this, "联系人和短信备份[备份数据功能体验]", "联系人和短信已备份，详情请查看附件！", sFile.getAbsolutePath(), mFile.getAbsolutePath());
								}
							}
						}).create().show();
				break;
			}
		}
	}

	/**
	 * 显示手机位置
	 */
	private void showLocation() {
		mLocClient = new LocationClient(this);
		mListener = new MyLocationListenner();
//		locData = new LocationData();
		mLocClient.registerLocationListener(mListener);
		// 设置相关参数
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true); // 打开gps
		option.setCoorType("bd09ll"); // 设置坐标类型
		option.setServiceName("com.baidu.location.service_v2.9");
		option.setPoiExtraInfo(true);//显示地址信息
		option.setAddrType("all");//所有的信息
		
		// if(null!=mSpanEdit.getText().toString())
		// {
		// boolean b = isNumeric(mSpanEdit.getText().toString());
		// if(b)
		// {
		// option.setScanSpan(Integer.parseInt(mSpanEdit.getText().toString()));
		// //设置定位模式，小于1秒则一次定位;大于等于1秒则定时定位
		// }
		// }
		option.setScanSpan(3000);

		// if(mPriorityCheck.isChecked())
		// {
		// option.setPriority(LocationClientOption.NetWorkFirst); //设置网络优先
		// }
		// else
		// {
		// option.setPriority(LocationClientOption.GpsFirst); //不设置，默认是gps优先
		// }
		option.setPriority(LocationClientOption.GpsFirst); // 不设置，默认是gps优先

		option.setPoiNumber(10);
		option.disableCache(true);
		mLocClient.setLocOption(option);
		mLocClient.start();
	}


	/** =============自定义类================ */

	/**
	 * 监听函数，又新位置的时候，格式化成字符串，输出到屏幕中
	 */
	public class MyLocationListenner implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null)
				return;
			String addr = "";
			if (location.getLocType() == BDLocation.TypeNetWorkLocation){
				addr = location.getAddrStr();
			}
			String locInfoTemp=  String.format(AppUtil.getString(FunctionActivity.this, R.string.loc_info_temp), addr,location.getLongitude(),location.getLatitude());
			Logger.d(TAG, locInfoTemp);
			new DialogBuilder(FunctionActivity.this)//
			.setMessage(locInfoTemp)//
			.setOnClickListener(new DialogInterface.OnClickListener() {//
						public void onClick(DialogInterface dialog, int position) {
						}
					}).create().show();
			if (mLocClient != null) {
				mLocClient.stop();
			}
		}

		public void onReceivePoi(BDLocation poiLocation) {
			if (poiLocation == null) {
				return;
			}
		}
	}

	@Override
	protected void onDestroy() {
		// 当前Activity销毁时停止定位
		if (mLocClient != null) {
			mLocClient.stop();
		}
		super.onDestroy();
		AppUtil.stopSound(mMediaPlayer);// 返回时结束声音播放
	}

}
